#import "TranscodingTools.h"

#include "qt-faststart.h"

@interface TranscodingTools ()

@end

@implementation TranscodingTools

/// 修改元数据位置
/// @param url mp4原视频的路径
/// @param completion 转码结束的回调
- (void)transcodingFrom:(NSURL *)url completion:(void (^)(NSString *outputPath))completion  {
    
    NSString *sanboxPath = nil; // 沙盒文件夹路径
    NSString *fileName = nil;   // 输出的文件名，例如：时分秒
    // 使用NSFileManager在沙盒文件中创建转码结果的文件夹
    // ...
    // ...
    NSString *outputPath = [sanboxPath stringByAppendingFormat:@"/%@.mp4", fileName];   // 输出视频的路径
    
    NSString *commandStr = [NSString stringWithFormat:@"qt-faststart!#$%@!#$%@", [url.absoluteString stringByReplacingOccurrencesOfString:@"file://" withString:@""], outpath];

    // 根据 !#$ 将指令分割为指令数组
    NSArray *argv_array = [commandStr componentsSeparatedByString:(@"!#$")];
    // 将OC对象转换为对应的C对象
    int argc = (int)argv_array.count;
    char** argv = (char**)malloc(sizeof(char*)*argc);
    for(int i=0; i < argc; i++) {
        argv[i] = (char*)malloc(sizeof(char)*1024);
        strcpy(argv[i],[[argv_array objectAtIndex:i] UTF8String]);
    }
    // 打印日志
    NSString *finalCommand = @"qt-faststart 运行参数:";
    for (NSString *temp in argv_array) {
        finalCommand = [finalCommand stringByAppendingFormat:@"%@", temp];
    }
    NSLog(@"%@", finalCommand);
    // 传入指令数及指令数组
    qtfaststart_main(argc, argv);
    // 转码结束，回调
    if (completion) {
        completion(outputPath)
    }
}

@end
